package com.example.seckilldemo.controller;

import com.example.seckilldemo.pojo.User;
import com.example.seckilldemo.service.IGoodsService;
import com.example.seckilldemo.service.IUserService;
import com.example.seckilldemo.vo.DetailVo;
import com.example.seckilldemo.vo.GoodsVo;
import com.example.seckilldemo.vo.RespBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * TODO 跳转到商品列表
 *
 * @author 59244
 * @date 2021/11/14 21:39
 */
@Controller
@RequestMapping("/goods")
@Slf4j
public class GoodsController {

    @Autowired
    IUserService userService;
    @Autowired
    IGoodsService goodsService;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    ThymeleafViewResolver thymeleafViewResolver;

    /**
     * 功能描述：商品列表  页面缓存优化
     * Windows优化前QPS：2261
     * 页面缓存优化后QPS：5122
     *
     * Linux优化前QPS：524
     *
     * @params:
     * @return：
     * @author: 59244
     * @time: 2021/11/21 15:09
     */
    @RequestMapping(value = "/tolist", produces = "text/html;charset=utf-8")
    @ResponseBody
    public String tolist(Model model, User user,
                         HttpServletRequest request, HttpServletResponse response){
        //项目刚开始写的 对user对象的校验， 后来用mvc对user入参进行同意的校验
//        log.info("随机生成的用户Cookie："+ticket);
//        if(StringUtils.isEmpty(ticket)){
//            return "login";
//        }
////        User user = (User) httpSession.getAttribute(ticket);
//        User user = userService.getUserByCookie(request, response, ticket);
//        if(user == null){
//            return "login";
//        }
        //从redis中获取页面缓存
        String html = (String) redisTemplate.opsForValue().get("goodsList");
        if(!StringUtils.isEmpty(html)){
            return html;
        }
        model.addAttribute("user",user);
        model.addAttribute("goodsList",goodsService.findGoodsVo());
        WebContext webContext = new WebContext(request, response, request.getServletContext(), request.getLocale(),
                model.asMap());
        html = thymeleafViewResolver.getTemplateEngine().process("goodList", webContext);
        if(!StringUtils.isEmpty(html)){
            redisTemplate.opsForValue().set("goodsList", html, 60, TimeUnit.SECONDS);
        }
        return html;
    }

    /**
     * 功能描述：商品详情页   URL缓存优化
     *
     * @params:
     * @return：
     * @author: 59244
     * @time: 2021/11/21 20:00
     */
    @RequestMapping(value = "/todetail/{goodsID}", produces = "text/html;charset=utf-8")
    @ResponseBody
    public String todetail(Model model, User user, @PathVariable Long goodsID,
                           HttpServletRequest request, HttpServletResponse response){
        //从redis中获取页面缓存
        String html = (String) redisTemplate.opsForValue().get("goodsDetail:" + goodsID);
        if(!StringUtils.isEmpty(html)){
            return html;
        }

        model.addAttribute("user", user);

        GoodsVo goodsVo = goodsService.findGoodsVoByGoodsId(goodsID);
        Date startDate = goodsVo.getStartDate();
        Date endDate = goodsVo.getEndDate();
        Date nowDate = new Date();
        //秒杀状态
        int secKillStatus = 0;
        //秒杀开始剩余时间
        int remainSeconds = 0;
        if(nowDate.before(startDate)){
            //秒杀未开始
            remainSeconds = (int)(startDate.getTime() - nowDate.getTime())/1000;
        }else if(nowDate.after(endDate)){
            //秒杀已结束
            secKillStatus = 2;
            remainSeconds = -1;
        }else{
            //秒杀进行中
            secKillStatus = 1;
            remainSeconds = 0;
        }
        model.addAttribute("secKillStatus", secKillStatus);
        model.addAttribute("remainSeconds", remainSeconds);
        model.addAttribute("goods", goodsVo);

        //将页面缓存到redis中 并返回
        WebContext webContext = new WebContext(request, response, request.getServletContext(), request.getLocale(),
                model.asMap());
        html = thymeleafViewResolver.getTemplateEngine().process("goodsDetail", webContext);
        if(!StringUtils.isEmpty(html)){
            redisTemplate.opsForValue().set("goodsDetail:"+goodsID,html,60,TimeUnit.SECONDS);
        }
        return html;
    }

    /**
     * 功能描述：商品详情页     页面静态化优化
     *
     * @params:
     * @return：
     * @author: 59244
     * @time: 2021/11/21 21:00
     */
    @RequestMapping(value = "/detail/{goodsID}")
    @ResponseBody
    public RespBean todetail(User user, @PathVariable Long goodsID){

        GoodsVo goodsVo = goodsService.findGoodsVoByGoodsId(goodsID);
        Date startDate = goodsVo.getStartDate();
        Date endDate = goodsVo.getEndDate();
        Date nowDate = new Date();
        //秒杀状态
        int secKillStatus = 0;
        //秒杀开始剩余时间
        int remainSeconds = 0;
        if(nowDate.before(startDate)){
            //秒杀未开始
            remainSeconds = (int)(startDate.getTime() - nowDate.getTime())/1000;
        }else if(nowDate.after(endDate)){
            //秒杀已结束
            secKillStatus = 2;
            remainSeconds = -1;
        }else{
            //秒杀进行中
            secKillStatus = 1;
            remainSeconds = 0;
        }
        DetailVo detailVo = new DetailVo();
        detailVo.setUser(user);
        detailVo.setGoodsVo(goodsVo);
        detailVo.setSecKillStatus(secKillStatus);
        detailVo.setRemainSeconds(remainSeconds);

        return RespBean.success(detailVo);
    }
}
